<?php

namespace mpend\modules\notice\controllers;

use common\components\wechat\MpWechat;
use common\helpers\ArrayHelper;
use common\models\notice\Notice;
use common\models\notice\NoticeCommit;
use common\models\notice\NoticeReceive;
use common\models\notice\ShowbizRole;
use mpend\modules\notice\models\NoticeSearch;
use mpend\modules\notice\models\NoticeView;
use Yii;
use mpend\components\Controller;
use mpend\modules\notice\models\NoticeForm;
use yii\data\ActiveDataProvider;
use yii\data\Pagination;
use yii\db\Exception;

class NoticeController extends Controller
{
    protected function rules()
    {
        return [
            [
                'allow' => true,
                'roles' => ['@'],
            ]
        ];
    }

    /**
     * @inheritdoc
     */
    protected function verbs()
    {
        return [
            '*' => ['POST'],
            'commit-list' => ['GET'],
            'search-notice' => ['GET'],
            'notice-page' => ['GET'],
        ];
    }

    /**
     * 创建/修改通告
     */
    public function actionCreate($id = null)
    {
        $model = new NoticeForm();
        $model->notice_id = $id;
        $model->user_id = $this->uid;
        if (!$model->load(Yii::$app->request->post(), '')) {
            parent::error('缺少信息');
        }
        return $model->save();
    }

    /**
     * 获取通告角色列表
     */
    public function actionNoticeRoleList()
    {
        return ShowbizRole::find()->active()->all();
    }

    /**
     * 获取所有通告列表
     * @return ActiveDataProvider
     * @throws \yii\base\InvalidConfigException
     */
    public function actionNoticeList()
    {
//        $query = NoticeView::find()->alias('t');
//        $query->joinWith('account account');
//        $query->andWhere(
//            [
//                't.status' => 10
//            ]
//        );
//        $query->orderBy([
//            'account.amount' => SORT_DESC,
//            't.created_at' => SORT_DESC
//        ]);
//        $pages = new Pagination(['totalCount' => $query->count(), 'pageSize' => 5, 'pageSizeParam' => false]);
//        $dataProvider = new ActiveDataProvider([
//            'query' => $query,
//            'pagination' => $pages
//        ]);
//        return $dataProvider;
        //
        $query = NoticeView::find()->alias('t');
        $query->joinWith('account account');
        $query->andWhere(
            [
                't.status' => 10
            ]
        );
        $topquery = clone $query;
        $topquery->orderBy([
            'account.amount' => SORT_DESC,
            't.created_at' => SORT_DESC
        ]);
//        $topquery->limit(5);
//        $list = ArrayHelper::diffrent($query->all(), $topquery->all());
        return $topquery->all();
    }

    public function actionNoticePage()
    {
        $query = NoticeView::find()->alias('t');
        $query->joinWith('account account');
        $query->andWhere(
            [
                't.status' => 10
            ]
        );
        $query->orderBy([
            'account.amount' => SORT_DESC,
            't.created_at' => SORT_DESC
        ]);
        $pages = new Pagination(['totalCount' => $query->count(), 'pageSize' => 5, 'pageSizeParam' => false]);
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => $pages
        ]);
        return $dataProvider;
    }

    /**
     * 获取登录用户发布的所有通告
     */
    public function actionMyNotice()
    {
        return Notice::find()->active()->andWhere(['user_id' => $this->uid])->all();
    }

    /**
     * 获取推荐的通告列表
     */
    public function actionRecomNoticeList()
    {
        return Notice::find()->active(Notice::STATUS_ACTIVE)->limit(4)->all();
    }

    /**
     * 获取通告详情
     */
    public function actionNoticeDetail()
    {
        $params = Yii::$app->request->post();
        if ($params) {
            $model = NoticeView::find()->active()->andWhere(['id' => $params['id']])->one();
            $model->hits++;
            $model->save();
            return $model;
        } else {
            return parent::error('缺少信息');
        }
    }

    /**
     * 下架通告
     */
    public function actionHideNotice()
    {
        $params = Yii::$app->request->post();
        $model = Notice::find()->andWhere(['id' => $params['id']])->one();
        if ($model) {
            $model->setAttributes([
                'status' => '0'
            ]);
            $transaction = Yii::$app->db->beginTransaction();
            try {
                if (!$model->save()) {
                    throw new Exception($model->getErrorMsg());
                }
                $transaction->commit();
            } catch (Exception $e) {
                // 记录回滚（事务回滚）
                $transaction->rollBack();
            }
            return $model;
        } else {
            return parent::error('该通告不存在');
        }
    }

    /**
     * 获取用户已投递的通告列表
     */
    public function actionDeliverNotice()
    {
        return NoticeSearch::find()->active()->andWhere(['user_id' => $this->uid, 'type' => 'resume'])->all();
    }

    /**
     * 发布评论
     */
    public function actionCommit()
    {
        $model = new NoticeCommit();
        if (!$model->load(Yii::$app->request->post(), '')) {
            return $model->loadError('缺少信息');
        }
        if (!$model->validate()) {
            return $model->dumpError('提交内容验证失败');
        }
        $model->user_id = $this->uid;
        $model->save();
        $noticemodel = Notice::findOne($model->notice_id);
        if (!$noticemodel) {
            return $model->loadError('没有此通告');
        }
        $nrmodel = new NoticeReceive();
        $nrmodel->setAttributes([
            'user_id' => $noticemodel->user_id,
            'notice_id' => $model->notice_id,
            'title' => '您的通告有了新的评论',
            'description' => '您的通告《' . $noticemodel->title . '》有了新的评论',
            'actor_id' => '0',
            'system_notice_id' => '1',
            'type' => 'commit'
        ]);
        $nrmodel->save();
    }

    /**
     * 获取通告的评论列表
     * @param $notice_id
     * @return array|\yii\db\ActiveRecord[]
     * @throws \yii\base\InvalidConfigException
     */
    public function actionCommitList($notice_id)
    {
        return NoticeCommit::find()->active()->andWhere(['notice_id' => $notice_id])->all();
    }

    /**
     * 搜索通告
     * @param null $key
     * @return array|\yii\db\ActiveRecord[]
     * @throws \yii\base\InvalidConfigException
     */
    public function actionSearchNotice($key = null)
    {
        $k = $key ? $key : '';
        if ($k) {
            /* @var $wechat MpWechat */
            $wechat = Yii::$app->get('wechat');
            $return = $wechat->msgSecCheck($k);
            if (is_array($return) && array_key_exists('code', $return) && array_key_exists('msg', $return) && $return['code'] == 87014) {
                return parent::error($return['msg']);
            }
        }
        //
        return NoticeView::find()->active()->andWhere([
            'or',
            ['like', 'title', $k],
            ['like', 'description', $k],
            ['like', 'location', $k]
        ])->andWhere(['status' => 10])->all();
    }
}
